package com.czy.moudle.exception.service.impl;

import com.czy.moudle.exception.domain.BaseExceptation;
import com.czy.moudle.exception.domain.ExceptionConfig;
import com.czy.moudle.exception.domain.enums.Type;
import com.czy.moudle.exception.service.BaseExceptionService;
import com.czy.moudle.exception.service.ExceptionConfigService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/***
 * @author 陈致远
 * @date 2016/11/28
 */
@Service("baseExceptionServiceImpl")
public class BaseExceptionServiceImpl implements BaseExceptionService {

    @Resource(name = "fileExceptionConfigServiceImpl")
    private ExceptionConfigService configService;

    @Override
    public BaseExceptation tarceException(Exception exception) {

        //判断exception是否属于BaseException
        if (exception instanceof BaseExceptation) {
            return (BaseExceptation) exception;
        } else {
            /**
             * 不属于BaseException的从ExceptionConfig中以异常类全名匹配；
             * 还没有找到的为未定义异常。
             */
            String key = exception.getClass().getName();

            Map<String, ExceptionConfig> configs = configService.loadExceptinConfigList();

            ExceptionConfig config = configs.get(key);

            //异常配置中是否包含异常类全名的key
            if(config == null){
                key = "EXP.UNKNOWN";
                config = configs.get(key);
                config.setErrType(Type.normal);
            }

            BaseExceptation be = BaseExceptation.buildException(config.getErrKey(), config.getErrCode(), config.getErrLevel(), config.getErrType());
            be.setContent(exception.getMessage());
            return be;
        }
    }

}
